package com.gitee.zycra.future.job.dao;

import com.gitee.zycra.future.job.common.model.JobDependence;
import com.gitee.zycra.jdbc.common.BaseDao;
import com.gitee.zycra.jdbc.common.CommonSelector;
import com.gitee.zycra.jdbc.enums.SQLConditionEnum;
import com.gitee.zycra.jdbc.enums.SQLLinkEnum;
import com.gitee.zycra.jdbc.util.SQLBlock;
import com.gitee.zycra.jdbc.util.SQLChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author zycra
 */
@Repository
public class JobDependenceDao extends BaseDao<JobDependence> {

    @Autowired
    private CommonSelector commonSelector;

    /**
     * 批量插入
     *
     * @param dependenceList 任务依赖信息对象集合
     * @return 插入条数
     */
    public int batchInsertJobDependence(List<JobDependence> dependenceList) {
        return batchInsertIntoTable(dependenceList);
    }

    /**
     * 根据父调度信息ID查询子任务ID
     *
     * @param parentId 父调度信息ID
     * @return 查询到的数据
     */
    public List<Long> selectChildIdByParentId(Long parentId) {
        return commonSelector.selectByParam(getJdbcTemplate(),
                "SELECT child_schedule_id FROM job_dependence WHERE deleted = 0 AND parent_schedule_id = ?",
                Long.class, List.of(parentId));
    }

    /**
     * 根据子调度信息ID查询父任务ID
     *
     * @param childScheduleId 子调度信息ID
     * @return 查询到的数据
     */
    public List<Long> selectParentIdByChildScheduleId(Long childScheduleId) {
        return commonSelector.selectByParam(getJdbcTemplate(),
                "SELECT parent_schedule_id FROM job_dependence WHERE deleted = 0 AND child_schedule_id = ?",
                Long.class, List.of(childScheduleId), false);
    }

    /**
     * 根据子调度信息ID集合查询父任务ID
     *
     * @param childScheduleIdList 子调度信息ID集合
     * @return 查询到的数据
     */
    public List<Long> selectParentIdByChildScheduleIdList(List<Long> childScheduleIdList) {
        SQLChain sqlChain = SQLChain.builder()
                .addBlock(SQLBlock.of(SQLLinkEnum.AND, "deleted", SQLConditionEnum.EQUALS, 0))
                .addBlock(SQLBlock.of(SQLLinkEnum.AND, "child_schedule_id", SQLConditionEnum.IN, childScheduleIdList.toArray()))
                .build();
        return commonSelector.selectByParam(getJdbcTemplate(),
                "SELECT parent_schedule_id FROM job_dependence" + sqlChain.getSQL(),
                Long.class, sqlChain.getParamList());
    }

    /**
     * 删除子任务的所有父任务依赖
     *
     * @param childScheduleId 子任务ID
     * @param operatorId      操作人ID
     * @param operatorName    操作人姓名
     * @return 删除条数
     */
    public int deleteChildDependence(Long childScheduleId, Long operatorId, String operatorName) {
        String sql = "UPDATE job_dependence SET deleted = 1, operator_id = ?, operator_name = ? WHERE child_schedule_id = ?";
        return getJdbcTemplate().update(sql, operatorId, operatorName, childScheduleId);
    }
}
